document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('registerForm');
    const messageDiv = document.getElementById('message');

    form.addEventListener('submit', async function(event) {
        event.preventDefault();

        const formData = new FormData(form);
        const payload = {
            firstName: formData.get('firstName'),
            lastName:  formData.get('lastName'),
            email:     formData.get('email'),
            password:  formData.get('password'),
        };

        try {
            const response = await fetch('/registration', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            if (response.ok) {
                const result = await response.json();
                messageDiv.textContent = 'Регистрация успешна!';
                messageDiv.classList.add('success');
                messageDiv.classList.remove('error');
                messageDiv.style.display = 'block';

                setTimeout(() => {
                    window.location.href = '/';
                }, 500);

            } else {
                messageDiv.textContent = 'Ошибка регистрации: ' + (await response.json()).detail;
                messageDiv.classList.add('error');
                messageDiv.classList.remove('success');
                messageDiv.style.display = 'block';
            }
        } catch (error) {
            messageDiv.textContent = 'Ошибка регистрации: ' + error.message;
            messageDiv.classList.add('error');
            messageDiv.classList.remove('success');
            messageDiv.style.display = 'block';
        }
    });
});